
package com.wobaby.util.log;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.DriverManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.ejb.FinderException;

import com.wobaby.util.config.Config;
import com.wobaby.util.config.ConfigChangedListener;
import com.wobaby.util.config.ConfigUtil;

// Referenced classes of package com.wobaby.util.log:
//            LogPrinter, Log

public class LogUtil
{

    public LogUtil()
    {
    }

    public static Collection getLogFileNames(int diff, boolean before)
    {
        return getLogUtil().getAllLogNames(diff, before);
    }

    public static String getSystemInfo()
    {
        return getLogUtil().getSystemInformation();
    }

    public static LogUtil getLogUtil()
    {
        if(s_logUtil == null)
            s_logUtil = new LogUtil();
        return s_logUtil;
    }

    public static String getLogNamePattern()
    {
        String prefix = Config.getConfig().get("cleandebuglogs/prefix", "tc.log");
        return getNamePattern(prefix);
    }

    public static String getSyslogLogNamePattern()
    {
        String syslog_prefix = Config.getConfig().get("cleandebuglogs/syslogprefix", "log/syslog_tc.log");
        if(!"log/syslog_tc.log".equals(syslog_prefix))
            syslog_prefix = syslog_prefix + "_" + "tc.log";
        return getNamePattern(syslog_prefix);
    }

    private static String getNamePattern(String prefix)
    {
        String directory = Config.getConfig().get("cleandebuglogs/directory", "");
        String pattern = Config.getConfig().get("cleandebuglogs/pattern", "%M-%D-%Y");
        StringBuffer buf = new StringBuffer("file:");
        buf.append(directory).append("/").append(prefix).append(".").append(pattern);
        if(sLogUtilTrace)
            sLogUtilLog.trace(null, "The name pattern for [" + prefix + "] is [" + buf + "].");
        return buf.toString();
    }

    private Collection getAllLogNames(int diff, boolean before)
    {
        String syslogLogDirectory = Config.getConfig().get("cleandebuglogs/directory", "");
        String syslogPrefix = Config.getConfig().get("cleandebuglogs/prefix", "tc.log");
        if(sLogUtilTrace)
            sLogUtilLog.trace(this, "The directory to contain TC syslog logs: " + syslogLogDirectory);
        Collection syslogLogNames = getLogNames(diff, before, syslogLogDirectory, syslogPrefix);
        String serverLogDirectory = Config.getConfig().get("cleandebuglogs/appserverlog/directory", "");
        String serverLogPrefix = Config.getConfig().get("cleandebuglogs/appserverlog/name", "server.log");
        if(sLogUtilTrace)
            sLogUtilLog.trace(this, "The directory to contain TC server logs: " + serverLogDirectory);
        Collection serverLogNames = getLogNames(diff, before, serverLogDirectory, serverLogPrefix);
        Collection result = new ArrayList();
        result.addAll(syslogLogNames);
        result.addAll(serverLogNames);
        return result;
    }

    private Collection getLogNames(int diff, boolean before, String directory, String pref)
    {
        final String prefix = pref;
        String pattern = Config.getConfig().get("cleandebuglogs/pattern", "%M-%D-%Y");
        Collection result = new ArrayList();
        File dir = new File(directory);
        if(!dir.isDirectory())
            return result;
        File files[] = dir.listFiles(new FilenameFilter() {

            public boolean accept(File f, String name)
            {
                return name.indexOf(prefix) != -1;
            }

        }
);
        if(files.length < 1)
            return result;
        SimpleDateFormat sdf = null;
        try
        {
            sdf = new SimpleDateFormat(buildPattern(pattern));
        }
        catch(IllegalArgumentException iae)
        {
            if(sLogUtilError)
                sLogUtilLog.error(this, "Bad dateformat pattern for a log file: " + pattern);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(10, -1 * diff);
        Date earliest = cal.getTime();
        if(sLogUtilTrace)
            sLogUtilLog.trace(this, "Logs to be sent after: " + earliest);
        for(int i = 0; i < files.length; i++)
        {
            String fullfilename = files[i].toString();
            String filename = files[i].getName();
            if(sLogUtilTrace)
                sLogUtilLog.trace(this, "The file: " + filename + " The result: " + fullfilename);
            int index = filename.lastIndexOf(prefix);
            if(index != 0)
            {
                if(sLogUtilTrace)
                    sLogUtilLog.trace(this, "Ignoring: " + filename);
                continue;
            }
            if(filename.equalsIgnoreCase(prefix))
            {
                if(sLogUtilTrace)
                    sLogUtilLog.trace(this, "Got current log: " + filename);
                result.add(fullfilename);
                continue;
            }
            index += prefix.length();
            index++;
            Date d = null;
            try
            {
                String subStr = filename.substring(index);
                if(sLogUtilTrace)
                    sLogUtilLog.trace(this, "Parsing logfile suffix: " + subStr);
                d = sdf.parse(subStr);
            }
            catch(ParseException pe)
            {
                if(sLogUtilInfo)
                    sLogUtilLog.info(this, "ParseException during parsing at index: " + index + " parsing filename: " + filename);
                continue;
            }
            if(sLogUtilTrace)
                sLogUtilLog.trace(this, "Parsed logs timestamp: " + d);
            if(before)
            {
                if(!earliest.before(d) && earliest.compareTo(d) != 0)
                    continue;
                result.add(fullfilename);
                if(sLogUtilTrace)
                    sLogUtilLog.trace(this, "Adding: " + d);
                continue;
            }
            if(!earliest.after(d) && earliest.compareTo(d) != 0)
                continue;
            result.add(fullfilename);
            if(sLogUtilTrace)
                sLogUtilLog.trace(this, "Adding: " + d);
        }

        return result;
    }

    private String buildPattern(String pattern)
    {
        if(pattern == null)
            return "";
        StringBuffer name = new StringBuffer();
        char s[] = pattern.toCharArray();
        for(int n = 0; n < s.length; n++)
            if(s[n] == '%' && n + 1 < s.length)
                switch(s[++n])
                {
                case 72: // 'H'
                    name.append("k");
                    break;

                case 100: // 'd'
                    name.append("EEE");
                    break;

                case 68: // 'D'
                    name.append("dd");
                    break;

                case 109: // 'm'
                    name.append("MMM");
                    break;

                case 77: // 'M'
                    name.append("MM");
                    break;

                case 121: // 'y'
                    name.append("yy");
                    break;

                case 89: // 'Y'
                    name.append("yyyy");
                    break;
                }
            else
                name.append(s[n]);

        if(sLogUtilTrace)
            sLogUtilLog.trace(this, "Pattern to be parsed:[" + pattern + "] and result: [" + name.toString() + "]");
        return name.toString();
    }

    private String getSystemInformation()
    {
        StringBuffer result = new StringBuffer();
        //result.append(ProductInfo.getLongVersionForCLI());
        Properties p = System.getProperties();
        result.append("\nSystem Properties:\n\n");
        String next;
        for(Enumeration e = p.propertyNames(); e.hasMoreElements(); result.append("\n").append(next).append(": ").append(p.getProperty(next)))
            next = (String)e.nextElement();

        result.append("\n").append("\n\nJVM System Memory:\n");
        Runtime run = Runtime.getRuntime();
        result.append("\n").append("Free Memory: [" + run.freeMemory() + "] bytes ");
        result.append("\n").append("Total Memory: [" + run.totalMemory() + "] bytes ");
        result.append("\n").append("Maximum Memory: [" + run.maxMemory() + "] bytes ");
        result.append("\n").append("Available Processors: [" + run.availableProcessors() + "]");
        result.append("\n").append("\nLicense: \n\n");
        /*try
        {
            String lines[][] = PermitManager.getInstance().getInfo();
            for(int i = 0; i < lines.length; i++)
            {
                String line[] = lines[i];
                result.append(line[i]).append("\n");
            }

        }
        catch(FinderException fe)
        {
            result.append("\n").append("License finding error: \n\n");
        }*/
        result.append("\n").append("\nDrivers: \n\n");
        //List allDrivers = DriverManager.getDriverManager().getAllDriverNames();
        String dname;
        /*for(Iterator iter = allDrivers.iterator(); iter.hasNext(); result.append(dname).append("\n"))
            dname = DriverManager.getDriverManager().getDriverDescriptionForName((String)iter.next(), true);

        DatabaseMonitor dbm = new DatabaseMonitor();
        DiagnosticResult dr = dbm.getDiagnostics(false);
        result.append("\n").append("\nDatabase Information: \n\n");
        result.append(dr.toString());
        DiskMonitor diskm = new DiskMonitor();
        DiagnosticResult dr2 = diskm.getDiagnostics(false);
        result.append("\n").append("\nDisk Information: \n\n");
        result.append(dr2.toString());
        BaseServerMonitor basem = new BaseServerMonitor();
        String threadNames = basem.getThreadNames();
        result.append("\n").append("\nThreads: \n\n");
        result.append(threadNames);*/
        return result.toString();
    }

    private static LogPrinter sLogUtilLog;
    private static boolean sLogUtilError;
    private static boolean sLogUtilInfo;
    private static boolean sLogUtilTrace;
    private static LogUtil s_logUtil;
    private static final String DEFAULT_LOG_FILE_NAME = "tc.log";
    public static final String DEFAULT_SYSLOG_NAME = "log/syslog";
    private static final String DEFAULT_SYSLOG_LOG_NAME = "log/syslog_tc.log";
    private static final String DEFAULT_LOG_DIRECTORY = "";
    private static final String DEFAULT_SERVER_LOG_DIRECTORY = "";
    private static final String DEFAULT_SERVER_LOG_FILE_NAME = "server.log";
    private static final String DEFAULT_LOG_NAME_SUFFIX_PATTERN = "%M-%D-%Y";

    static 
    {
        sLogUtilLog = Log.getLog("debuglog");
        sLogUtilError = sLogUtilLog.configuredFor(75);
        sLogUtilInfo = sLogUtilLog.configuredFor(25);
        sLogUtilTrace = sLogUtilLog.configuredFor(0);
        ConfigUtil.registerListener(new ConfigChangedListener() {

            public void configChanged()
            {
                LogUtil.sLogUtilLog = Log.getLog("debuglog");
                LogUtil.sLogUtilError = LogUtil.sLogUtilLog.configuredFor(75);
                LogUtil.sLogUtilInfo = LogUtil.sLogUtilLog.configuredFor(25);
                LogUtil.sLogUtilTrace = LogUtil.sLogUtilLog.configuredFor(0);
            }

        }
);
    }





}